<?php

include '../../libraries/dbconfig.php';
include '../../libraries/messages.php';
session_start();

//If customer selected
//if ($_SESSION['customer']) {
    //If items presents      
    if ($_SESSION['display']) {

        if ($_SESSION['total']) {
            $total = $_SESSION['total'];
            $customer = $_SESSION['customer'];
            $result = $_SESSION['display'];


            $alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            $length = 11;
            for ($i = 0; $i < $length; $i++) {
                $ran = rand(0, strlen($alpha) - 1);
                $key .= substr($alpha, $ran, 1);
            }

            //Inserting data into bills table
            $bill_insert = mysql_query("INSERT INTO bills (date, billto, total, discount, amount, vat, randomkey)
VALUES ('$total[date]', '$customer', '$total[total_rate]', '$total[total_discount]', '$total[bill_total]', '$total_vat', '$key' )");

            $bill = mysql_query("select billno from bills where randomkey = '$key'") or die(mysql_error());
            $bill_data = mysql_fetch_array($bill);
            $billno = $bill_data['billno'];

            for ($row = 0; $row < count($result); $row++) {

                $productid = $result[$row]['productid'];
                $qty = $result[$row]['qty'];
                $price = $result[$row]['price'];
                $amount = $result[$row]['amount'];
                $discount=$result[$row]['discount'];
                 $vat=$result[$row]['vat'];
                $billdetails_insert = mysql_query("INSERT INTO billdetails (billno, productid, qty, rate, discount, vat, total) VALUES ('$billno', '$productid', '$qty', '$price', '$discount', '$vat', '$amount')") or die(mysql_error());
                $stock=mysql_query("select sold from invoicedetails where productid = $productid");
                 $stock_data = mysql_fetch_array($stock);
           
                $product_sold = $stock_data['sold'] + $qty;
                $invoicedetails_update = "UPDATE invoicedetails SET  sold = $product_sold  WHERE productid = $productid";
    mysql_query($invoicedetails_update) or die("Error: ".mysql_error());
                        
            }
            echo $message[18];
            unset($_SESSION['display']);
            unset($_SESSION['total']);
          
        } else {
            echo $message[17];
        }
    } else {
        echo $message[17];
    }
//} else {
    //echo $message[16];
//}
?>